package com.jindu.producer.system.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author jarvis
 */
public class AuthRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     *设计权限系统后,需要重写
     */
    private static final Set<String> PERMISSION = new HashSet(Arrays.asList(new String[]{"view","edit"}));

    private static final String ROLE = "admin";

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = JwtUtils.getUsername(principals.toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(ROLE);
        simpleAuthorizationInfo.addStringPermissions(PERMISSION);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        /**
         * 解密获得username,和user_id
         */
        String username = JwtUtils.getUsername(token);
        String userId=JwtUtils.getUserId(token);

        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        if (! JwtUtils.verify(token,username,userId)) {
            throw new AuthenticationException("Username or password error");
        }

        return new SimpleAuthenticationInfo(token, token, "AuthRealm");
    }
}
